package edu.whu.notepal.controller;

import edu.whu.notepal.dto.NoteDTO;
import edu.whu.notepal.dto.Result;
import edu.whu.notepal.pojo.Note;
import edu.whu.notepal.service.NoteService;
import edu.whu.notepal.utils.RedisClient;
import edu.whu.notepal.utils.RedisConstants;
import edu.whu.notepal.utils.UserHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description 便签的控制器
 * @author 陈磊
 */
@RestController
@RequestMapping("/note")
public class NoteController {

    @Resource
    NoteService noteService;

    @Resource
    RedisClient redisClient;

    @GetMapping("/{id}")
    public Result<NoteDTO> getById(@PathVariable("id")Long id){
        NoteDTO noteDTO = redisClient.queryWithPassThrough(RedisConstants.NOTE_INFO_KEY, id,
                NoteDTO.class, noteService::getDetailsById, RedisConstants.NOTE_INFO_TTL, TimeUnit.MINUTES);
        return Result.success(noteDTO);
    }

    @GetMapping("/user")
    public Result<List<Note>> getByUserId(Long userId, Long startIndex, Long size){
        List<Note> list = noteService.getByUserId(userId,startIndex,size);
        return Result.success(list);
    }

    /**
     * 删除id对应的便签 逻辑删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable("id")Long id){
        noteService.removeById(id);
        return Result.success("删除成功！");
    }

    @PostMapping
    public Result<String>save(@RequestBody NoteDTO noteDTO){
        noteDTO.setPublisherId(UserHolder.getUser().getId());
        noteDTO.setPrivateChat(noteDTO.getExceptedNumbers()==1);
        if(noteDTO.getPrivateChat()){
            noteService.save(noteDTO);
        }else{
            noteService.saveWithGroup(noteDTO);
        }
        return Result.success("保存成功!");
    }

    @GetMapping("/myNotes")
    public Result<List<Note>> myNotes(Long startIndex,Long size){
        Long id = UserHolder.getUser().getId();
        List<Note> list = noteService.getByUserId(id,startIndex,size);
        return Result.success(list);
    }

    @GetMapping("/column")
    public Result<List<NoteDTO>> columnNotes(Long columnId, Long startIndex,Long size){
        List<NoteDTO> notes = noteService.getNotesByColumnId(columnId, startIndex, size);
        return Result.success(notes);
    }

}